﻿// if (/\.cnexpo\.com$/i.test(window.location.hostname)) document.domain = 'cnexpo.com';
if (typeof _dutuwang == 'undefined') _dutuwang = {};

// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
$.rand = function (len) {
    len = len || 32;
    var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var pwd = '';
    for (i = 0; i < len; i++)
        pwd += chars.charAt(Math.floor(Math.random() * chars.length));
    return pwd;
}

$.ajaxSetup({ xhrFields: { withCredentials: true }, crossDomain: true });
$(function () {
    _dutuwang.init();
    var gt = $('#gotop.gotop').click(function () { $('html,body').animate({ scrollTop: 0 }, 300); return false; });
    $(window)
        .resize(function () {
            _dutuwang.center($('.floatbox'));
            _dutuwang.center($('#upMsg'));
            $('.g_ucard').remove();
        })
        .scroll(function () {
            if (_dutuwang.toplock != null) $(window).scrollTop(_dutuwang.toplock);
            if (gt.length > 0) {
                if ($(window).scrollTop() > 50) gt.slideDown(300);
                else gt.slideUp(200);
            }
        })
    ;
    $(document)
        .click(function () { $('select[size]').click(); })
        .keydown(function (e) {
            if (e.keyCode == 27) _dutuwang.fb.hide($('.floatbox:last'));
            for (var i = 0; _dutuwang.event.keydown.data && i < _dutuwang.event.keydown.data.length; i++) {
                _dutuwang.event.keydown.data[i].call(e);
            }
        })
    ;
    $('form[search]').each(function () {
        var f = this;
        $(f).submit(function () {
            _dutuwang.form.trim($(f).find('input'));
            if (f.k.value == '' || f.k.value.length < 2) { f.k.focus(); return false; }
            if ($(f.t).val() == 'p') $(f).attr('action', '/u/designer');
            else $(f).attr('action', '/work/');
            $(f.t).attr('disabled', true);
            f.submit();
        }).find('input[name=k]').blur(function () { if ($(this).val() == '') $(this).css({ color: '' }); }).focus(function () { $(this).css({ color: 'inherit' }); });
    });
});

var _dutuwang = {
    toplock: null,
    event: {
        keydown: {
            data: [],
            add: function (name, call) { this.data.push({ name: name, call: call }) },
            remove: function (name) { for (var i = 0; this.data && i < this.data.length; i++) { if (this.data[i].name == name) this.data.splice(i, 1); } }
        }
    },
    init: function (e) {
        if (typeof e == 'undefined') e = $(document);
        e.find('form input').attr('autocomplete', 'off');
        //end
    },
    con: {
        regemail: /^[a-zA-Z0-9-_]+(\.[a-zA-Z0-9_-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z]+)+$/,
        regurl: new RegExp('^https?://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]$'),
        regmobile: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/
    },
    scroll: function (v, f) {
        var f = f;
        $('html,body').animate({ scrollTop: v }, 300, function () { if (typeof f == 'function') { f(); f = null; } });
    },
    center: function (v) {
        v.each(function () {
            var e = $(this);
            e.css('height', 'auto');
            var x = 0, y = 0;
            if ($.browser && $.browser.msie && $.browser.version == '6.0') {
                x = $(window).scrollLeft() + ($(window).width() - e.outerWidth()) / 2;
                y = $(window).scrollTop() + ($(window).height() - e.outerHeight()) / 2;
            }
            else {
                x = ($(window).width() - e.outerWidth()) / 2;
                y = ($(window).height() - e.outerHeight()) / 2;
            }
            if (y < 0) { y = 0; e.css('height', $(window).height() - (e.outerHeight() - e.height()))/*.css('overflow', 'auto')*/; }
            e.css('top', y).css('left', x);
        });
        return v;
    },
    checkall: function (all, array) {
        all.click(function () { array.prop('checked', all.prop('checked') ? true : false); });
    },
    checkallval: function (array) {
        var v = '';
        array.each(function () { v += (v == '' ? '' : ',') + $(this).val(); });
        return v;
    },
    inputlength: function (input, maxlength, tip) {
        input.keyup(function (event) { var cl = input.val().replace(/\r?\n/g, "00").length; tip.html(maxlength - cl < 0 ? ('<em style="color:red;">' + (maxlength - cl) + '</em>') : maxlength - cl); }).keyup();
    },
    loadEditor: function (id) {
        var editor = 'editor_'+id;
        window[editor] = KindEditor.create('#'+id, {
            filterMode: true,
            allowFileManager: false,
            allowImageRemote: false,
            autoHeightMode: true,
            width:'100%',
            items: [
                'removeformat', 'justifyleft', 'justifycenter', 'justifyright',
                'formatblock', 'fontsize', 'forecolor', 'hilitecolor', 'bold',
                'italic', 'underline'
            ],
            afterCreate: function () {
                this.sync();
                this.loadPlugin('autoheight');
            },
            afterBlur: function () {
                this.sync();
            }
        });
    }
}


/**
 * 判断是否手机号码格式
 * @param mobile
 * @returns {boolean}
 */
function isMobile(mobile) {
    if (!/^1\d{10}$/.test(mobile)) {
        return false;
    }
    return true;
}
/**
 * 判断是否邮箱格式
 * @param email
 * @returns {boolean}
 */
function isEmail(email){
    if (!/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,}$/.test(email)) {
        return false;
    }
    return true;
}

/**
 * 判断是否固定电话
 * @param tel
 * @returns {boolean}
 */
function isTel(tel) {
    if (!/^0\d{2,3}-?\d{7,8}$/.test(tel)) {
        return false;
    }
    return true;
}

/**
 * 判断是否网址
 * @param url
 * @returns {boolean}
 */
function isUrl(url) {
    if (!/(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(url)){
        return false;
    }
    return true;
}

/**
 * 判断是否数字
 * @param n
 * @returns {boolean}
 */
function isNumber(n){
    return !isNaN(parseFloat(n)) && isFinite(n);
}
$.ajaxSetup({ cache: false });
var xhrback = function (ts, xhr) { if (ts == 'error') { if (ts == 'timeout') { layer.alert('超时！'); return false; } else if (xhr.status == 404) { layer.alert('404！'); return false; } else if (xhr.status == 500) { layer.alert('500！'); return false; } } return true; }

//window.onbeforeunload = function () { return '未保存的信息可能会丢失，是否继续？'; };

$(function () {
	$(document)
		.on('click', function (event) {
			var dd = $(event.target).is('.g_dropdown.show') ? $(event.target) : $(event.target).parents('.g_dropdown.show:first');
			if (!dd.length) $('.g_dropdown.show:last').removeClass('show');
		})
		.delegate('a', 'click', function () {
			if ($(this).attr('href') == '') return false;
			else if ($(this).attr('href') == '#') {
				if ($(this).attr('pn')) _fm.panel.open($(this).attr('pn'), $(this));
				else if ($(this).attr('for') == 'dropdown') {
					var ep = $(this).parent();
					var dd = ep.find('.g_dropdown');
					if (dd.is('.show')) { dd.removeClass('show'); }
					else {
						ep.css('position', 'relative');
						dd.css('top', ep.outerHeight()).addClass('show');
					}
				}
				return false;
			}
			else if ($(this).attr('pn') && $(this).parents('body>.panel').length > 0) { _fm.panel.open($(this).attr('pn'), $(this)); return false; }
		})
		.delegate('body>.page form[action], body>.panel form[action]', 'submit', function () {
			var f = $(this);
			if (f.attr('target')) return;
			f.find('input[type=submit]').prop('disabled', true);
			var ip = /^post$/i.test(f.attr('method'));
			var ac = !ip ? f.attr('action').replace(/\?.+$/g, '') + '?' + $.param(f.serializeArray()) : f.attr('action');
			if (!ip && /^#/.test(ac)) { window.location.hash = ac; return false; }
			if ($(this).parents('body>.panel').length > 0) {
				var pn = $(this).parents('body>.panel');
				pn.find('>div').load(ac, ip ? f.serializeArray() : null, function (rt, ts, xhr) { $(this).find('[cancel]').click(function () { _fm.panel.close(); }); if (xhrback(ts, xhr)) { _dutuwang.init($(this)); if (typeof _fm.load == 'function') { _fm.load($(this)); _fm.load = null; } } }); ///*************
			}
			else {
				var pg = $(this).parents('body>.page');
				pg.load(ac, ip ? f.serializeArray() : null, function (rt, ts, xhr) { if (xhrback(ts, xhr)) { _dutuwang.init($(this)); if (typeof _fm.load == 'function') { _fm.load($(this)); _fm.load = null; } } }); ///*************
			}
			return false;
		})
		.keydown(function (e) {
			if (e.keyCode == 27) _fm.panel.close();
		})
		.delegate('input,textarea,select', 'keydown', function (e) { if (e.keyCode == 27) return false; });

	//核心
	window.onhashchange = function (e, noflush) { var p = window.location.hash.replace(/^#/g, ''); if (p == '') return; if (!noflush) { $('body>.page').empty(); _fm.panel.close(); } $('body>.page').css({ opacity: noflush ? 1 : 0 }).load(_fm.rootpath + p, function (rt, ts, xhr) { _fm.page.menu($(this)); if (!noflush) $(this).stop().animate({ opacity: 1 }, 200); if (xhrback(ts, xhr)) { if ($(this).find('>[full]').length > 0) $('body').addClass('full'); else $('body').removeClass('full'); _dutuwang.init($(this)); if (typeof _fm.load == 'function') { _fm.load($(this)); _fm.load = null; } } }); }
	var p = window.location.hash.replace(/^#/g, '');
	if (p == '') p = 'main.html';
	_fm.page.go(p);
	window.onhashchange();

	//菜单处理
	$('body>.left>.menu>li>a.row').click(function () {
		var show = !$(this).hasClass('on');
		var tr = $('body>.left>.menu>li>a.row.on');
		var sr = $('body>.left>.menu .sub a.row.on');
		if (/^#?$/.test($(this).attr('href'))) {
			tr.removeClass('on').next('.sub').hide();
			if (show) $(this).addClass('on').next('.sub:hidden').fadeIn(200);
			return false;
		}
		tr.removeClass('on').next('.sub').fadeOut(200);
		if (show) $(this).addClass('on').next('.sub:hidden').fadeIn(200);
		sr.removeClass('on');
	});
	$('body>.left>.menu .sub a.row').click(function () {
		$('body>.left>.menu .sub a.row').removeClass('on');
		$(this).addClass('on');
	});

	//end
});

var _fm = {
	rootpath: '/member/',//路径修改
	load: null,
	page: {
		reload: function (flush) { window.onhashchange(null, typeof flush == 'undefined' ? true : !flush); },
		go: function (path) { window.location.hash = '#' + path; },
		turn: function (e, pidx, pcount) {
			var t;
			if (!pidx) pidx = parseInt((t = $(e).parents('.g_mpage').find('.t')).val());
			else pidx = parseInt(pidx);
			if (isNaN(pidx)) { if (t) t.val('').focus(); return; }
			if (t && (pidx < 1 || (pcount && pidx > pcount))) { t.val('').focus(); return; }
			var pn = $(e).parents('body>.panel');
			if (pn.length <= 0) {
				var u = window.location.href.replace(/&?p=[^&]*/, '');
				window.location.href = (u + (/\?/.test(u) ? '&' : '?') + 'p=' + pidx).replace(/\?&/, '?');
			}
			else if (typeof pn.attr('path') != 'undefined') {
				var p = pn.attr('path').replace(/&?p=[^&]*/, '');
				_fm.panel.reload((p + (/\?/.test(p) ? '&' : '?') + 'p=' + pidx).replace(/\?&/, '?'))
			}
		},
		menu: function (p) {
			$('body>.left>.menu>li a.row').each(function () {
				var r = $(this);
				if (!r.attr('href') || r.attr('href') == '' || r.attr('href') == '#') return;
				else if (window.location.hash.indexOf(r.attr('m') ? '#' + r.attr('m') : r.attr('href')) == 0) {
					if (!r.hasClass('on')) r.click();
					var r = r.parents('.sub').prev('a.row');
					if (!r.hasClass('on')) r.click();
					return false;
				}
			});
		}
	},
	panel: {
		reload: function (path) {
			var pl = $('body>.panel'); if (pl.length <= 0) return;
			pl.attr('path', path).find('>div').hide().empty().load(_fm.rootpath + path, function (rt, ts, xhr) { $(this).fadeIn(100).find('[cancel]').click(function () { _fm.panel.close(); }); if (xhrback(ts, xhr)) { _dutuwang.init($(this)); if (typeof _fm.load == 'function') { _fm.load($(this)); _fm.load = null; } } });
		},
		open: function (path, e) {
			$('body>.panel').remove();
			var pl = $('<div class="panel"><a href="#" onclick="return false;" class="close" cancel><i class="fa fa-step-forward"></i></a><div></div></div>').attr('path', path).appendTo($(document.body));
			pl.find('[cancel]').click(function () { _fm.panel.close(); });
			pl.find('>div').load(_fm.rootpath + path, function (rt, ts, xhr) { $('html').css({ overflow: 'hidden' }); pl.show().animate({ marginRight: 0 }, 300); $(this).fadeIn(700).find('[cancel]').click(function () { _fm.panel.close(); }); if (xhrback(ts, xhr)) { _dutuwang.init($(this)); if (typeof _fm.load == 'function') { _fm.load($(this)); _fm.load = null; } } });
		},
		close: function () { $('html').css({ overflow: '' }); $('body>.panel').remove(); }
	}
}